<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" :disabled="this.type == 'edit' ? true : false" @filterChange="changeHandle" />
    <BreakSpace label="维护区域" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :disabled="status == '1001' ? false : true" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <BreakSpace label="采购发票明细" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <FilterTable
      ref="table"
      :columns="columns"
      columnsRef="partPartOtherRepairPartBuyInvoicAddForm"
      :dataSource="dataSource"
      height="300px"
      :isMemoryPagination="false"
      :isPagination="false"
      :onCellChange="changeCells"
      :onRowSelectChange="SelectHandle"
      :onSyncTableData="tahbleHandle"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <!-- :onSummationChange="getSum" -->
      <!-- <template slot="controls">
        <el-button :disabled="status == '1001' ? false : true" type="primary" @click="allSelect">全 选</el-button>
        <el-button :disabled="status == '1001' ? false : true" @click="allDestroy">全 销</el-button>
      </template> -->
    </FilterTable>
    <div style="height:10px"></div>
    <BreakSpace label="结算明细" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <FilterTable
      ref="table1"
      :columns="columns1"
      columnsRef="partPartOtherRepairPartBuyInvoicAddForm1"
      :fetchapi="fetchApi1"
      height="auto"
      :params="fetchParams1"
      :isMemoryPagination="true"
      selectionType="multiple"
      :datakey="'rows'"
      :onSyncTableData="payHandle"
      :onColumnsChange="columns => (this.columns1 = columns)"
      :onRowSelectChange="arr => (this.onSelectedRows1 = arr)"
    >
      <template slot="moreActions">
        <span v-if="status == '1001'" @click="() => delTableRows()">删除数据</span>
      </template>
      <template slot="controls">
        <el-button :disabled="type == 'edit' ? true : false" icon="el-icon-plus" type="primary" @click="addTableRow()">新 增</el-button>
      </template>
    </FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDrawer">关 闭</el-button>
      <multiuse-button :disabled="type == 'edit' && status == '1001' ? false : true" type="primary" :click="inputInvoice.bind(this, '1002')">发票认证</multiuse-button>
      <!-- <el-button :disabled="type == 'edit' && status == '1002' ? false : true" @click="inputInvoice('1001')">取消发票认证</el-button> -->
      <multiuse-button :disabled="type == 'edit' && status == '1002' ? false : true" :click="inputInvoice.bind(this, '1001')">取消发票认证</multiuse-button>
      <el-button :disabled="type == 'edit' && status == '1001' ? false : true" @click="closeDrawer">删 除</el-button>
      <!-- <el-button :disabled="status == '1001' ? false : true" type="primary" :click="saveDrawer">保 存</el-button> -->
      <el-button :disabled="status == '1001' ? false : true" type="primary" :loading="loading" @click="saveDrawer">保存</el-button>
    </div>
    <BaseDialog :visible.sync="showProvideSearch" title="供应商搜索帮助" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ProvideSearch ref="provideSearch" @onConfirm="setProvide" @close="closeProvideSearch" />
    </BaseDialog>
  </div>
</template>

<script>
/**
 * @Author: 刘加明
 **/
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { jsonToHump, arrayObjDeWeight } from '@/utils/index';
import { getInvoiceItem, getProvider, getAllUser, postPartInvoice, inputInvoice, getInvoice, getInvoiceItemX, getInvoiceSett } from '@/api/part/partOther/repairPartBuyInvoic';
import ProvideSearch from '@/pages/part/partPurchase/purchaseOrder/provideSearchHelper.vue';
import { notifyAction, isFormEmpty } from '@/utils';
import { getInvoiceType } from '@/api/finance/repair/receivables';

export default {
  name: 'AddForm',
  components: {
    ProvideSearch
  },
  mixins: [dictionary],
  props: ['Type', 'AuthId'],
  data() {
    this.saveData = null;
    this.status = '1001';
    this.sum = '';
    return {
      tableSyncData: [], // 同步的table数据
      payData: [], // 结算表格的数据
      topFilterList: this.createtopFilterList(),
      formList: this.createFormList(),
      columns: this.createTableColumns(),
      // fetchParams: { xhrAbort: true },
      // fetchApi: getInvoiceItem,
      dataSource: [],
      onSelectedRows: [],
      loading: false,
      columns1: this.createTableColumns1(),
      fetchParams1: { xhrAbort: true },
      fetchApi1: getInvoiceSett,
      onSelectedRows1: [],
      showProvideSearch: false,
      providerData: null,
      delData: [],
      status: '1001',
      type: null,
      payNum: '',
      authId: null,
      disabled: 0
    };
  },
  computed: {},
  watch: {
    type: {
      handler(val) {
        // console.log('type', val);
        if (val == 'edit') {
          // console.log('disabledType')
          this.$emit('changeType', 'edit');
          for (const item of this.topFilterList) {
            item.disabled = true;
          }
          this.topFilterList = [...this.topFilterList];
          this.formList.find(item => item.fieldName === 'type').disabled = true;
          this.formList = [...this.formList];
        }
      }
    },
    status: {
      handler(val) {
        // console.log('status', val);
        if (val == '1002') {
          this.topFilterList = [...this.topFilterList];
          this.formList.find(item => item.fieldName === 'type').disabled = true;
          this.formList.find(item => item.fieldName === 'invoiceNo').disabled = true;
          this.formList.find(item => item.fieldName === 'invoiceDate').disabled = true;
          this.formList = [...this.formList];
        }
      }
    }
  },
  created() {
    console.log('this.Type', 666, this.Type, 666);
    if (this.type == 'edit') {
      // console.log('disabledType')
      for (const item of this.topFilterList) {
        item.disabled = true;
      }
      this.formList.find(item => item.fieldName === 'type').disabled = true;
    }
  },
  mounted() {
    this.createBaseTable();
    this.getProvider();
    this.getInvoiceType();
    this.getAllUser();
    this.openModel();
    this.disabled = this.Type == 'edit' ? 1 : 0;
    this.$refs.table.$refs.pageTable && this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(this.tableSyncData);
    this.$refs.table1.$refs.pageTable && this.$refs.table1.$refs.pageTable.SET_DISABLE_SELECT(this.payData);
  },
  methods: {
    createtopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'customerCode',
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.openProvideSearch}></el-button>;
          },
          rules: [{ required: true, message: '请选择供应商', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '采购单号',
          fieldName: 'providerCode',
          itemList: []
        },
        {
          type: 'RANGE_DATE',
          label: '入库日期',
          style: { minWidth: '200px' },
          fieldName: 'finishedDateStr|finishedDateEn'
        }
      ];
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '单据编号',
          fieldName: 'billNo',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '供应商',
          fieldName: 'providerCode',
          itemList: [],
          disabled: true,
          rules: [{ required: true, message: '请选择供应商', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '发票类型',
          fieldName: 'type',
          itemList: [],
          rules: [{ required: true, message: '请选择发票类型', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '发票号',
          fieldName: 'invoiceNo',
          rules: [{ required: true, message: '请输入发票号', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '发票日期',
          fieldName: 'invoiceDate',
          dateType: 'date',
          rules: [{ required: true, message: '请选择发票日期', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '金额',
          precision: 2,
          fieldName: 'amount',
          disabled: true,
          min: -Infinity,
          change: val => {
            this.changeBalance(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '税额',
          precision: 2,
          fieldName: 'tax',
          min: -Infinity,
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '不含税金额',
          precision: 2,
          min: -Infinity,
          fieldName: 'costAmount',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'status',
          itemList: [
            { text: '录入', value: '1001' },
            { text: '提交', value: '1002' }
          ],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '操作员',
          fieldName: 'createdBy',
          itemList: [],
          disabled: true
        },
        {
          type: 'DATE',
          label: '认证单日期',
          fieldName: 'confirmDate',
          dateType: 'date',
          disabled: true
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 110,
        //   fixed: 'left',
        //   render: props => {
        //     return (
        //       <div>
        //         <el-button size="mini" type="text" onClick={()=>this.openDetail(props.row)}>
        //           编辑
        //         </el-button>
        //         <el-button size="mini" type="text" onClick={()=>this.openDetail(props.row)}>
        //           明细
        //         </el-button>
        //       </div>
        //     );
        //   }
        // },
        {
          title: '采购单号',
          dataIndex: 'purchaseCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'R3发票号',
          dataIndex: 'R3IncoiceNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '认证数量',
        //   dataIndex: 'qty',
        //   sorter: true,
        //   summation: true,
        //   precision: 2,
        //   // summationUnit: '个',
        //   editable: this.status == '1001' ? true : false,
        //   editRequired: true,
        //   editType: 'number',
        //   filter: true,
        //   hidden: true,
        //   filterType: 'number'
        // },
        // {
        //   title: '认证金额',
        //   dataIndex: 'amt',
        //   hidden: true,
        //   sorter: true,
        //   summation: true,
        //   // summationUnit: '元',
        //   precision: 2,
        //   render: props => {
        //     props.row.amt = props.row.qty * props.row.inPriceTax;
        //     return <span>{props.row.amt.toFixed(2)}</span>;
        //   },
        //   filter: true,
        //   filterType: 'number'
        // },
        // {
        //   title: '认证税额',
        //   dataIndex: 'tax',
        //   hidden: true,
        //   sorter: true,
        //   summation: true,
        //   // summationUnit: '元',
        //   // editable: true,
        //   editRequired: true,
        //   editType: 'number',
        //   precision: 2,
        //   render: props => {
        //     // console.log(props.row.amt, 'amt', props.row.costAmt, 'costAmt');
        //     props.row.tax = props.row.amt - props.row.costAmt;
        //     // console.log(props.row.tax, 'tax', props.row.tax.toFixed(2));
        //     return <span>{props.row.tax.toFixed(2)}</span>;
        //   },
        //   filter: true,
        //   filterType: 'number'
        // },
        // {
        //   title: '认证不含税金额',
        //   dataIndex: 'costAmt',
        //   hidden: true,
        //   sorter: true,
        //   summation: true,
        //   // summationUnit: '元',
        //   // editable: true,
        //   editRequired: true,
        //   editType: 'number',
        //   precision: 2,
        //   render: props => {
        //     props.row.costAmt = props.row.amt / (1 + props.row.purTaxRate);
        //     return <span>{props.row.costAmt.toFixed(2)}</span>;
        //   },
        //   filter: true,
        //   filterType: 'number'
        // },
        {
          title: '未认证数量',
          dataIndex: 'qty',
          sorter: true,
          summation: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '未认证金额',
          dataIndex: 'amt',
          summation: true,
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '未认证税额',
          dataIndex: 'tax',
          summation: true,
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '未认证不含税金额',
          dataIndex: 'costAmt',
          summation: true,
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '数量',
          dataIndex: 'inQuantity',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '金额',
          dataIndex: 'inAmTax',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '税额',
          dataIndex: 'taxAmount',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税金额',
          dataIndex: 'inAmount',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '采购单价',
          dataIndex: 'inPriceTax',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '采购税率',
          dataIndex: 'purTaxRate',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '仓库代码',
          dataIndex: 'storageCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '仓库名称',
          dataIndex: 'storageName',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createTableColumns1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '结算方式类别',
          dataIndex: 'type',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算方式',
          dataIndex: 'settType',
          sorter: true,
          editable: this.disabled == 1 ? false : true,
          // editable: this.disabled == 1 ? false : this.status == '1001' ? true : false,
          editRequired: true,
          editType: 'select',
          editItems: this.createDictList('8044'),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8044')
        },
        {
          title: '结算日期',
          dataIndex: 'settDate',
          sorter: true,
          editable: this.disabled == 1 ? false : true,
          editRequired: true,
          editType: 'date-picker',
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '结算金额',
          dataIndex: 'amt',
          sorter: true,
          summation: true,
          // summationUnit: '元',
          editable: this.disabled == 1 ? false : true,
          editRequired: true,
          editType: 'number',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          editable: this.disabled == 1 ? false : true,
          editType: 'input',
          filter: true,
          filterType: 'input'
        }
      ];
    },
    SelectHandle(val) {
      let sumNum = 0; // 合计金额
      let sumTax = 0; // 税额
      let inTax = 0; // 不含税
      for (let i = 0; i < val.length; i++) {
        console.log('666', 666);
        val[i].qty = val[i].inQuantity;
        val[i].amt = val[i].inAmTax;
        val[i].costAmt = val[i].inAmount;
        val[i].tax = val[i].taxAmount;
        sumNum += val[i].amt;
        sumTax += val[i].tax;
        inTax += val[i].costAmt;
      }
      this.formList.find(x => x.fieldName == 'amount').initialValue = sumNum;
      this.formList.find(x => x.fieldName == 'tax').initialValue = sumTax;
      this.formList.find(x => x.fieldName == 'costAmount').initialValue = inTax;
      let deleteRows = [];
      // deleteRows = this.onSelectedRows.filter(item => {
      //   return !this.onSelectedRows.find(item2 => item2._uid == item._uid);
      // });
      // console.log('this.onSelectedRows开始', this.onSelectedRows);
      deleteRows = this.onSelectedRows.filter(item => {
        return !val.find(item2 => item2._uid == item._uid);
      });
      console.log(deleteRows, 9090);
      deleteRows.forEach(item => {
        this.tableSyncData.find(item3 => item3._uid == item._uid).qty = 0;
        this.tableSyncData.find(item3 => item3._uid == item._uid).amt = 0;
        this.tableSyncData.find(item3 => item3._uid == item._uid).costAmt = 0;
        this.tableSyncData.find(item3 => item3._uid == item._uid).tax = 0;
      });
      this.onSelectedRows = val;

      console.log('this.onSelectedRows结束', this.onSelectedRows);
    },
    openModel() {
      // console.log(this.Type, 'this.Type', this.AuthId, 'this.AuthId');
      this.type = this.Type;
      this.authId = this.AuthId;
      console.log(this.type, 'openModel');
      if (this.type == 'add') {
        this.formList.find(item => item.fieldName === 'invoiceDate').initialValue = moment().format('YYYY-MM-DD');
      }
      if (this.type == 'edit') {
        this.getInvoice(this.authId);
      }
    },
    // 清理页面所有组件
    clearModel() {
      this.BaseTable.EXECUTE_DELETE(this.onSelectedRow);
      this.BaseTable1.EXECUTE_DELETE(this.payData);
      this.$refs.formPanel.RESET_FORM();
      this.$refs.topFilter.RESET_FORM();
    },
    // 声明表格组件
    createBaseTable() {
      this.BaseTable = this.$refs.table.$refs.pageTable;
      this.BaseTable1 = this.$refs.table1.$refs.pageTable;
    },
    tahbleHandle(list) {
      this.tableSyncData = list;
      if (this.type == 'edit') {
        this.$refs.table.$refs.pageTable && this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(this.tableSyncData);
      }
      console.log('syncDataChange=>val', this.tableSyncData);
      // val = this.dataSource
    },
    payHandle(val) {
      this.payData = val;
      this.payNum = 0;
      for (let i = 0; i < this.payData.length; i++) {
        this.payNum += +this.payData[i].amt;
      }
      console.log(val, 'payHandle');
      if (this.type == 'edit') {
        this.$refs.table1.$refs.pageTable && this.$refs.table1.$refs.pageTable.SET_DISABLE_SELECT(this.payData);
      }
      // val = this.dataSource
    },
    // topFilter 搜索
    async changeHandle(val) {
      let data = _.cloneDeep(val);
      data.customerCode = this.providerData.customerCode;
      // console.log(this.providerData, val, data, '搜索')
      this.$refs.table.START_LOADING();
      let res = await getInvoiceItem(data);
      if (res.resultCode == 200) {
        // console.log('res.data', res.data);
        for (let i = 0; i < res.data.length; i++) {
          res.data[i].qty = 0;
          res.data[i].amt = 0;
          res.data[i].costAmt = 0;
          res.data[i].tax = 0;
        }
        this.dataSource = JSON.parse(JSON.stringify(res.data));
        this.formList.find(x => x.fieldName === 'providerCode').initialValue = this.providerData.customerCode;
      }
      this.$refs.table.STOP_LOADING();
    },
    // 保存表单验证信息
    formChangeHandle(val) {
      this.saveData = val;
    },
    // 获取供应商
    async getProvider() {
      const res = await getProvider();
      // console.log(res)
      this.formList.find(item => item.fieldName === 'providerCode').itemList = res.data.rows.map(x => ({ value: x.customerCode, text: x.customerName }));
    },
    // 获取发票类型
    async getInvoiceType() {
      const res = await getInvoiceType();
      // console.log(res)
      this.formList.find(item => item.fieldName === 'type').itemList = res.data.map(x => ({ value: x.INVOICE_TYPE_CODE + '', text: x.INVOICE_TYPE_NAME }));
    },
    // 获取操作人
    async getAllUser() {
      const res = await getAllUser();
      let salerResult = arrayObjDeWeight(res.data, 'userId');
      // console.log(res, '所有员工');
      this.formList.find(item => item.fieldName === 'createdBy').itemList = salerResult.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    // 编辑时获取表单
    async getInvoice(authId) {
      const res = await getInvoice(authId);
      // console.log(res)
      if (res.resultCode == 200) {
        jsonToHump(res.data);
        // console.log(res.data)
        this.status = res.data.status;
        this.columns = this.createTableColumns();
        this.columns1 = this.createTableColumns1();
        this.getInvoiceItemX(this.authId);
        this.getInvoiceSett(this.authId);
        for (let [key, value] of Object.entries(res.data)) {
          this.formList.some(item => {
            if (item.fieldName === key) {
              item.initialValue = value;
              return true;
            }
          });
        }
      }
    },
    // 编辑时获取表格
    async getInvoiceItemX(authId) {
      const res = await getInvoiceItemX(authId);
      // console.log(res)
      if (res.resultCode == 200) {
        // this.BaseTable.EXECUTE_INSERT(res.data)
        this.dataSource = res.data;
        // this.$nextTick(()=>{
        //   console.log(this.BaseTable.originData, 'originData')
        // })
      }
    },
    // 编辑时获取结算表格
    async getInvoiceSett(authId) {
      const res = await getInvoiceSett(authId);
      // console.log(res);
      if (res.resultCode == 200) {
        for (const item of res.data.rows) {
          jsonToHump(item);
          item.settType = Number(item.settType);
        }
        this.BaseTable1.EXECUTE_INSERT(res.data.rows);
      }
    },
    // 单据认证-取消认证
    async inputInvoice(status) {
      // let id = this.formList.find(item => item.fieldName === 'billNo').initialValue
      const res = await inputInvoice(this.authId, status);
      if (res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '保存成功!' });
        this.closeDrawer();
      }
    },
    // 打开供应商弹窗
    openProvideSearch(data) {
      this.showProvideSearch = true;
    },
    // topFilter搜索后给表单供应商赋值
    setProvide(data) {
      if (data) {
        this.topFilterList.find(x => x.fieldName === 'customerCode').initialValue = data.customerName;
        this.providerData = {
          customerCode: data.customerCode,
          customerName: data.customerName
        };
        // console.log(data,'供应商数据')
      }
    },
    // 关闭供应商弹窗
    closeProvideSearch(data) {
      this.showProvideSearch = false;
    },
    // 表单编辑事件
    changeCells(keys, obj) {
      /* let list = this.BaseTable.dataSource;
      // console.log(keys, obj, '数据');
      let key = Object.keys(keys)[0];
      let a = key.substring(key.indexOf('|') + 1); */
    },
    // 获取表格合计信息
    getSum(val) {
      // console.log(val, 'sum')
      this.formList.find(x => x.fieldName == 'amount').initialValue = val.find(x => x.dataIndex == 'amt').value;
      // this.formList.find(x => x.fieldName == 'tax').initialValue = val.find(x => x.dataIndex == 'tax').value;
      // this.formList.find(x => x.fieldName == 'costAmount').initialValue = val.find(x => x.dataIndex == 'costAmt').value;
    },
    // 全选
    allSelect() {
      let list = this.BaseTable.originData;
      // console.log(this.BaseTable)
      for (const item of list) {
        item.qty = item.inQuantity;
        item.amt = item.inAmTax;
        item.tax = item.taxAmount;
        item.costAmt = item.inAmount;
      }
    },
    // 全销
    allDestroy() {
      let list = this.BaseTable.originData;
      // console.log(this.BaseTable)
      for (const item of list) {
        item.qty = 0;
        item.amt = 0;
        item.tax = 0;
        item.costAmt = 0;
      }
    },
    // 合计表格添加新数据
    addTableRow() {
      let row = {
        flag: 'A',
        type: '使用预付',
        amt: 0,
        settType: 80441007,
        settDate: moment().format('YYYY-MM-DD')
      };
      this.BaseTable1.EXECUTE_INSERT(row);
    },
    // 合计表格删除数据
    delTableRows() {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          for (const item of this.onSelectedRows1) {
            // console.log(item, 'settId')
            if (item.settId) {
              this.delData.push(item.settId);
            }
          }
          // console.log(this.delData, 'delData');
          this.BaseTable1.EXECUTE_DELETE(this.onSelectedRows1);
        })
        .catch(() => {});
    },
    // 新增-编辑保存
    async saveDrawer() {
      let formData = await this.$refs.formPanel.GET_FORM_DATA();
      let diff = this.formList.find(x => x.fieldName == 'amount').initialValue;
      console.log('this.tableSyncData', this.tableSyncData);
      console.log('this.onSelectedRows', this.onSelectedRows);
      if (this.onSelectedRows.length < 1) {
        return this.$notify.error({ title: '提示信息', message: '请至少选择一条发票明细' });
      }
      // 校验结算明细结算方式不能重复
      if (this.payData && this.payData.length) {
        let hasRepeatRow = false; // 是否有重复项
        let obj = {};
        this.payData.forEach(item => {
          obj[item.settType] ? (hasRepeatRow = true) : (obj[item.settType] = item);
        });
        if (hasRepeatRow) return this.$notify.warning({ title: '提示信息', message: '结算明细中支付方式不能重复' });
      }
      // 校验金额和结算金额
      if (diff != this.payNum) {
        this.$notify.error({ title: '提示信息', message: '结算金额总和必须等于已勾选未认证金额总和' });
      } else {
        this.saveData = null;
        // this.$refs.formPanel.SUBMIT_FORM();
        // 校验表单必填字段并提示
        let formData = await this.$refs.formPanel.GET_FORM_DATA();
        if (formData[0]) {
          let keys = Object.keys(formData[0]);
          // console.log(keys);
          return notifyAction(formData[0][keys[0]][0].message, 'warning');
        } else {
          this.saveData = formData[1];
        }

        if (this.saveData != null && !this.BaseTable.GET_REQUIRED_ERROR() && !this.BaseTable1.GET_REQUIRED_ERROR()) {
          this.$confirm('是否确认保存?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              this.loading = true;
              try {
                console.log('type=>', this.type, 'type');
                // invoiceItem: this.BaseTable.originData, // 采购发票明细
                // invoiceSett: this.BaseTable1.dataSource // 结算明细
                // console.log(this.saveData, this.BaseTable.originData, this.BaseTable1.dataSource, '保存数据')

                // this.onSelectedRows.forEach(item => {

                //   return (item.itemId = this.tableSyncData.find(item2 => item2._uid == item._uid).itemId);
                // });
                // 保存后后太返回的数量有问题，前端处理一下
                for (let i = 0; i < this.tableSyncData.length; i++) {
                  if (Number(this.tableSyncData[i].inQuantity) == 0) {
                    this.tableSyncData[i].inQuantity = 0;
                  }
                }
                let params = {
                  ...this.saveData,
                  invoiceItem: this.type == 'add' ? this.onSelectedRows : this.tableSyncData, // this.tableSyncData,全量
                  invoiceSett: this.payData
                };
                if (this.type == 'add') {
                  params.flag = 'A';
                } else {
                  params.authId = this.authId;
                  params.ids = this.delData;
                }
                console.log('params', params, '你过来啊');
                let res = await postPartInvoice(params);
                // console.log('res',res)
                if (res.resultCode == 200) {
                  this.$notify.success({ title: '提示信息', message: '保存成功!' });
                  // 保存后返回authID，重新请求数据
                  this.authId = res.data;
                  if (this.type == 'add') {
                    this.type = 'edit';
                  }
                }
                this.disabled = 1; // 保存后明细列表不可编辑
                this.$refs.table.$refs.pageTable && this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(this.tableSyncData);
                this.$refs.table1.$refs.pageTable && this.$refs.table1.$refs.pageTable.SET_DISABLE_SELECT(this.payData);
                this.clearModel();
                this.getInvoice(this.authId);
              } catch (err) {
                console.error(err);
              }
              this.loading = false;
            })
            .catch(() => {});
        } else {
          this.$notify.error({ title: '提示信息', message: '有必填项未填写!' });
        }

        /* if(this.type == 'add') {
        this.type = 'edit'
      }
      this.clearModel() */
      }
    },
    // 关闭本页
    closeDrawer() {
      this.$emit('close', false);
    }
  }
};
</script>

<style lang="less" scoped></style>
